<?php
	date_default_timezone_set('America/Argentina/Buenos_Aires');

	define("VALID_USER_ID", "10152700940819030");

	define("APP_ID", "519942634775590");
	define("SECRET", "5ea51129a4ca16efdaa478bbddeb1465");
	define("APP_CANVAS", "https://apps.facebook.com/pagepostercool/");

	define("URL_MSG", "https://www.solo-dilo.com/index.php?content_id=");
	define("FAN_PAGE_NAME", "Solo Dilo");

 	include_once('../db/dbcon.php');
	// Facebook PHP SDK v4.0.11

	// include required files form Facebook SDK

	require_once( '../Facebook/HttpClients/FacebookHttpable.php' );
	require_once( '../Facebook/HttpClients/FacebookCurl.php' );
	require_once( '../Facebook/HttpClients/FacebookCurlHttpClient.php' );

	require_once( '../Facebook/Entities/AccessToken.php' );
	require_once( '../Facebook/Entities/SignedRequest.php' );

	require_once( '../Facebook/FacebookSession.php' );
	require_once( '../Facebook/FacebookRedirectLoginHelper.php' );
	require_once( '../Facebook/FacebookRequest.php' );
	require_once( '../Facebook/FacebookResponse.php' );
	require_once( '../Facebook/FacebookSDKException.php' );
	require_once( '../Facebook/FacebookRequestException.php' );
	require_once( '../Facebook/FacebookOtherException.php' );
	require_once( '../Facebook/FacebookAuthorizationException.php' );
	require_once( '../Facebook/GraphObject.php' );
	require_once( '../Facebook/GraphSessionInfo.php' );

	use Facebook\HttpClients\FacebookHttpable;
	use Facebook\HttpClients\FacebookCurl;
	use Facebook\HttpClients\FacebookCurlHttpClient;

	use Facebook\Entities\AccessToken;
	use Facebook\Entities\SignedRequest;

	use Facebook\FacebookSession;
	use Facebook\FacebookRedirectLoginHelper;
	use Facebook\FacebookRequest;
	use Facebook\FacebookResponse;
	use Facebook\FacebookSDKException;
	use Facebook\FacebookRequestException;
	use Facebook\FacebookOtherException;
	use Facebook\FacebookAuthorizationException;
	use Facebook\GraphObject;
	use Facebook\GraphSessionInfo;

	error_reporting(E_ALL);

	$user_token = null;
	$page_token = null;

	// IE compatible
	header('P3P: CP="NOI ADM DEV PSAi NAV OUR STP IND DEM"');

	// start session
	session_start();

	// init app with app id and secret
	FacebookSession::setDefaultApplication( APP_ID, SECRET );

	// login helper with redirect_uri
	$helper = new FacebookRedirectLoginHelper( APP_CANVAS );

	// see if a existing session exists
	if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
		// create new session from saved access_token
		$session = new FacebookSession( $_SESSION['fb_token'] );

		// validate the access_token to make sure it's still valid
		try {
			if ( !$session->validate() ) {
				$session = null;
			}
		} catch ( Exception $e ) {
			// catch any exceptions
			$session = null;
		}
	}  

	// Try to create session by saved token
	if ( !isset( $session ) ) {
		loadTokens();
		$session = new FacebookSession( $user_token );

		// validate the access_token to make sure it's still valid
		try {
			if ( !$session->validate() ) {
				$session = null;
			}
		} catch ( Exception $e ) {
			// catch any exceptions
			$session = null;
		}
	}

	if ( !isset( $session ) || $session === null ) {
		// no session exists

		try {
			$session = $helper->getSessionFromRedirect();
		} catch( FacebookRequestException $ex ) {
			// When Facebook returns an error
			// handle this better in production code
			print_r( $ex );
		} catch( Exception $ex ) {
			// When validation fails or other local issues
			// handle this better in production code
			print_r( $ex );
		}

	}

	// see if we have a session
	if ( isset( $session ) ) {

		// save the session
		$_SESSION['fb_token'] = $session->getToken();
		// create a session using saved token or the new one we generated at login
		$session = new FacebookSession( $session->getToken() );

		// graph api request for user data
		$request = new FacebookRequest( $session, 'GET', '/me' );
		$response = $request->execute();
		// get response
		$user_profile = $response->getGraphObject()->asArray();
		
		$access_token = $_SESSION['fb_token'];
		$user_token = $access_token;

		// Check if its me!
		if ($user_profile['id'] == VALID_USER_ID)
			updateTokens($session);
		
		updatePostedContentsDB();

		// CODE TO EXCECUTE
		if (isset($_REQUEST['post_photo'])) {
			postPhoto($session);
		}

	} else {
		echo '<script>top.location.href="'.$helper->getLoginUrl( array( 'manage_pages', 'publish_actions', 'publish_stream', 'user_photos' ) ).'";</script>';
	}

	function loadTokens() {
		global $mysqli;
		global $user_token;
		global $page_token;

		$user_token_query = $mysqli->query("SELECT value FROM page_poster_global_parameters WHERE name='user_token'");

		if ($user_token_query->num_rows > 0)
			$user_token = $user_token_query->fetch_assoc()['value'];

		$page_token_query = $mysqli->query("SELECT value FROM page_poster_global_parameters WHERE name='page_token'");

		if ($page_token_query->num_rows > 0)
			$page_token = $page_token_query->fetch_assoc()['value'];
	}

	function updateTokens($session) {
		global $mysqli;
		global $user_token;
		global $page_token;

		$response = (new FacebookRequest(
				$session, 'GET', '/me/accounts?fields=name,access_token', array(
			'access_token' => $session->getToken()
			)
		))->execute()->getGraphObject();

		$pages = $response->getProperty('data')->asArray();
		$page_access_token = null;
		for ($i = 0; $i < count($pages); $i++) {
			if ($pages[$i]->name == FAN_PAGE_NAME) {
				$page_token = $pages[$i]->access_token;
				break;
			}
		}

		$mysqli->query("INSERT INTO page_poster_global_parameters (name, value) VALUES ('user_token', '".$user_token."') ON DUPLICATE KEY UPDATE value='".$user_token."'");
		$mysqli->query("INSERT INTO page_poster_global_parameters (name, value) VALUES ('page_token', '".$page_token."') ON DUPLICATE KEY UPDATE value='".$page_token."'");

		echo $mysqli->error;
	}

	function updatePostedContentsDB() {
		global $mysqli;

		$contentsToAdd_query = $mysqli->query("SELECT contents.content_id FROM contents WHERE contents.content_id NOT IN ( SELECT page_poster_contents.content_id FROM page_poster_contents ) AND contents.allowed_to_fan_page = 1");

		if ($contentsToAdd_query->num_rows > 0) {
			$mysqli->autocommit(false);

			while ($row = $contentsToAdd_query->fetch_assoc()) {
				$mysqli->query("INSERT INTO page_poster_contents (content_id, posted) VALUES (".$row['content_id'].", 0)");
			}
			
			$mysqli->commit();
			$mysqli->autocommit(true);
		}

	}

	function postPhoto($session) {
		global $mysqli;
		global $page_token;

		$contentsToPost_query = $mysqli->query("SELECT content_id FROM page_poster_contents WHERE posted = 0 ORDER BY RAND() LIMIT 1");

		if ($contentsToPost_query->num_rows == 0)
			return;

		$contentIdToPost = $contentsToPost_query->fetch_assoc()['content_id'];

		try {

			$imagePath = '../contentImages/'.$contentIdToPost.'.png';
			$imageFormat = 'image/png';


			$response = (new FacebookRequest(
					$session, 'POST', '/solodiloya/photos', array(
				'source' => new CURLFile($imagePath, $imageFormat),
				'message' => URL_MSG.$contentIdToPost,
				'no_story' => 'false',
				'published' => 'true',
				'access_token' => $page_token
				)
			))->execute()->getGraphObject();

			echo "Posted with id: " . $response->getProperty('id');
			$mysqli->query("UPDATE page_poster_contents SET posted_date='".date('Y-m-d H:i:s')."', posted=1, post_id=".$response->getProperty('id')." WHERE content_id=".$contentIdToPost);

		} catch(FacebookRequestException $e) {
			echo "Exception occured, code: " . $e->getCode();
			echo " with message: " . $e->getMessage();
		}   
	}


?>
